package com.timothy.gfund.service;

import java.util.Date;
import java.util.List;

import com.sina.oefund.SinaOEFundClient;
import com.sina.stock.SinaStockClient;
import com.sina.util.StringUtil;
import com.timothy.gfund.bean.NotifySettingBean;
import com.timothy.gfund.notification.NotificationBuild;
import com.timothy.junk.calculate.GFundCalculator;
import com.timothy.junk.common.parse.ParseXML;
import com.timothy.junk.common.util.DateUtil;
import com.timothy.junk.common.util.SPUtil;
import com.timothy.junk.gfund.bean.GFundBean;
import com.timothy.junk.gfund.bean.GFundBeanResult;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class NotifyService extends IntentService {
	 public static final String LOG_TAG = "NotifyService";
	 
	 public static final boolean RUNNING = true;
	 public static final int TIME_INTERVAL = 30;

	  Context mContext;
	  SharedPreferences sp;
	  NotifySettingBean bean;
	  boolean ifNotify;
	 
	  public boolean getNotify(NotifySettingBean nBean){
		  String notfiyFlag = nBean.getIsNotify();
		  Date startTime = DateUtil.getTime(nBean.getStartHour(), nBean.getStartMinute());
		  Date endTime = DateUtil.getTime(nBean.getEndHour(), nBean.getEndMinute());
		  
		  Date nowTime = DateUtil.getNowTime();
		  Log.i(LOG_TAG,"startTime:" + startTime.getTime());
		  Log.i(LOG_TAG,"endTime:" + endTime.getTime());
		  Log.i(LOG_TAG,"nowTime:" + nowTime.getTime());
		  if("Yes".equalsIgnoreCase(notfiyFlag)){
			  if(nowTime.getTime()>=startTime.getTime() && endTime.getTime() <= endTime.getTime()){
				  return true;
			  }
		  }
		  return false;
	  }
	  
	  /** 
	   * A constructor is required, and must call the super IntentService(String)
	   * constructor with a name for the worker thread.
	   */
	  public NotifyService() {
	      super("NotifyService");
	      Log.i(LOG_TAG,"NotifyService()...");
//	      mContext = getApplicationContext();
	  }

	  /**
	   * The IntentService calls this method from the default worker thread with
	   * the intent that started the service. When this method returns, IntentService
	   * stops the service, as appropriate.
	   */
	  @Override
	  protected void onHandleIntent(Intent intent) {
		  Log.i(LOG_TAG,"onHandleIntent()...");
		  
		  mContext = this.getApplicationContext();
		  sp = getSharedPreferences("GFundApp",MODE_PRIVATE);
		  
	      // Normally we would do some work here, like download a file.
//	      long endTime = System.currentTimeMillis() + 100 *1000;
	      while (RUNNING) {
	          synchronized (this) {
	              try {
	            	  wait(TIME_INTERVAL*1000);
	            	  
	        		  bean = SPUtil.getNotifySettingBean(sp);
	        		  ifNotify = getNotify(bean);
	        		  
	            	  //set if notification due setting in sp
	        		  if(ifNotify){
	        			  Log.i(LOG_TAG,"NotifyService running...");
		                  loadData();
		                  setNotification();
	        		  }else{
	        			  Log.i(LOG_TAG,"NotifyService.stopSelf()...");
	        			  stopSelf();
	        		  }
	              } catch (Exception e) {
	              }
	          }
	      }
	  }

	  List<GFundBeanResult> gFundResultList;
	  List<GFundBean> gFundList;
	  
	  public void loadData(){
		  Log.i(LOG_TAG,"loadData()...");
		  gFundList = ParseXML.getGFundList(mContext);
		  for(GFundBean bean:gFundList){
			  Log.i(LOG_TAG,bean.getIndex());
		  }
		  GFundCalculator cal = new GFundCalculator(gFundList);
		  cal.initialAllInputData();
		  cal.getStockData(SinaStockClient.getInstance());
		  cal.getFundData(SinaOEFundClient.getInstance());
		  cal.calculateResult();
		  gFundResultList = cal.getResultDataList();
//		  for(GFundBean bean:gFundResultList){
//			  Log.i(LOG_TAG,bean.toString());
//		  }
      }
	  
	  public void setNotification(){
		  Log.i(LOG_TAG,"setNotification()...");
		  
		  if(sp==null){
			  Log.i(LOG_TAG,"Can not get SharedPreferences !");
		  }
		  
		  StringBuilder sb = new StringBuilder();
		  String firstFundIndex = null;
		  for(GFundBeanResult rBean:gFundResultList){
			  String spValue = sp.getString(rBean.getIndex(), null);
			  if(spValue!=null){
				  Log.i(LOG_TAG," spValue:"+spValue);
				  
				  String[] spArray = spValue.split(":");
				  int notify = Integer.valueOf(spArray[0]);
				  double sCeil = Double.valueOf(spArray[1]);
				  double sFloor = Double.valueOf(spArray[2]);
				  
				  Log.i(LOG_TAG,rBean.getIndex()+ " discount:" + String.valueOf(rBean.getDiscount()));
				  
				  //set notify message
				  double discount = rBean.getDiscount()* 100;
				  if(notify == 1){
					  if(discount>=sCeil || discount<= sFloor){
						  if(firstFundIndex == null || "".equalsIgnoreCase(firstFundIndex)){
							  firstFundIndex = rBean.getIndex();
						  }
						  Log.i(LOG_TAG,"Notify Fund:" + rBean.getIndex());
						  sb.append(rBean.getFundMName()+" " + StringUtil.formatData2Deci(rBean.getDiscount()*100)+"%"+" "); 
					  }					  
				  }
			  }else{
				  Log.i(LOG_TAG,"Can not get " + rBean.getIndex() + " from SharedPreferences");
			  }
		  }
		  
		  if(sb.length()>0){
//			  Log.i(LOG_TAG,"Start setNotification():"+sb.toString());
			  NotificationBuild.issueNotification(firstFundIndex,sb.toString(), mContext);
			  Log.i(LOG_TAG,"setNotification() successfully!");
			  gFundResultList = null;
		  }
	  }
	  
	  @Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		Log.i(LOG_TAG,"onDestroy()...");
	}
}
